import {
	getCartListAPI,
	addCartAPI,
	deleteCartAPI,
	updateCartAPI,
	updateAllCartAPI,
	mergeCartAPI
} from '@/apis/cart.js'
import { ref, computed } from 'vue'
import { useUserStore } from './user.js'
import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', () => {
	const userStore = useUserStore()
	const isLogin = computed(() => userStore.userInfo.token)
	const cartList = ref([])

	const getCartList = async () => {
		if (isLogin.value) {
			const res = await getCartListAPI().then((res) => res.data)
			cartList.value = res.result
		}
	}
	const allCount = computed(() => cartList.value.reduce((acc, cur) => acc + cur.count, 0))
	const selectedCount = computed(() => cartList.value.filter((item) => item.selected).reduce((acc, cur) => acc + cur.count, 0))
	const cartTotalPrice = computed(() => cartList.value.filter((item) => item.selected).reduce((acc, cur) => acc + cur.count * cur.price, 0))
	const allSelected = computed(() => cartList.value.every((item) => item.selected))

	const addCart = async (goods) => {
		const { skuId, count } = goods;
		if (isLogin.value) {
			await addCartAPI({ skuId, count });
		}
		const item = cartList.value.find((item) => item.skuId === goods.skuId)
		if (item) {
			item.count += count
		} else {
			cartList.value.push(goods)
		}

	}
	const deleteCart = (skuId) => {
		const index = cartList.value.findIndex((item) => item.skuId === skuId)
		if (index > -1) {
			if (cartList.value[index].count > 1) {
				cartList.value[index].count -= 1
			} else {
				cartList.value.splice(index, 1)
			}
		} else {
			ElMessage.warning('商品已删除')
		}
	}
	
	const delCart = async (skuId) => {
		if (isLogin.value) {
			await deleteCartAPI([skuId]);
		}
		deleteCart(skuId)
	}


	const changeCart = async (goods) => {
		if (isLogin.value) {
			await updateCartAPI(goods.skuId, goods.selected, goods.count);
		}
		const index = cartList.value.findIndex((item) => item.skuId === goods.skuId)
		if (index > -1) {
			cartList.value[index].selected = goods.selected
			cartList.value[index].count = goods.count
		} else {
			ElMessage.warning('商品不存在')
		}

	}

	const selectAll = async (selected) => {
		if (isLogin.value) {
			await updateAllCartAPI(selected, cartList.value.map((item) => item.skuId));
		}
		cartList.value.forEach((item) => {
			item.selected = selected
		})
	}

	const mergeCart = async () => {
		if (isLogin.value) {
			const cartArr = cartList.value.map(item => ({ skuId: item.skuId, count: item.count, selected: item.selected }))
			await mergeCartAPI(cartArr);
			cartList.value = []
			getCartList();
		}
	}

	const clearCart = () => {
		cartList.value = []
	}

	return {
		cartList,
		allCount,
		selectedCount,
		cartTotalPrice,
		allSelected,
		getCartList,
		addCart,
		delCart,
		deleteCart,
		changeCart,
		selectAll,
		mergeCart,
		clearCart
	}
})